<template>
  <div v-if="createAuth">
    <page-header
      :title="ruleForm.id ? $t('m.branch_Edit') : $t('m.branch_Create')"
      is-emphasize
    >
      <el-button @click="submit()">{{ $t('m.save') }}</el-button>
    </page-header>
    <div class="detail_div container">
      <div class="detail_left">
        <div class="detail_left_div" style=" padding-bottom: 20px;">
          <el-form
            label-position="top"
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm1"
          >
            <div class="create_title2">{{ $t('m.Push_name') }}*</div>
            <el-form-item prop="sendName">
              <el-input
                v-model="ruleForm.sendName"
                :placeholder="$t('m.Please_enter')"
                clearable
                maxlength="20"
                show-word-limit
                style="width:390px;"
              ></el-input>
            </el-form-item>
            <div class="create_title2">{{ $t('m.Push_time') }}*</div>
            <el-form-item
              :style="ruleForm.sendMethod == 2 ? 'margin-bottom:0;' : ''"
            >
              <el-radio-group v-model="ruleForm.sendMethod">
                <el-radio :label="1">{{ $t('m.Push_now') }}</el-radio>
                <el-radio :label="2">{{
                  $t('m.Push_specified_time')
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="ruleForm.sendMethod == 2" prop="sendTime">
              <el-date-picker
                v-model="ruleForm.sendTime"
                style="width:390px;"
                popper-class="el_date_picker"
                type="datetime"
                value-format="timestamp"
                :placeholder="$t('m.pleaseChoose')"
                :picker-options="pickerOptions2"
              >
              </el-date-picker>
            </el-form-item>

            <div class="create_title2">{{ $t('m.Push_users') }}*</div>
            <el-form-item
              :style="ruleForm.sendType != 0 ? 'margin-bottom:0;' : ''"
            >
              <el-radio-group
                v-model="ruleForm.sendType"
                @input="notUser = false"
              >
                <el-radio :label="0">{{ $t('m.All_users') }}</el-radio>
                <el-radio :label="1">{{ $t('m.Specify_user') }}</el-radio>
                <el-radio :label="2">{{ $t('m.Specify_user_group') }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              v-if="ruleForm.sendType == 1"
              style="margin-bottom:8px"
            >
              <el-input
                v-model="params.search"
                :placeholder="$t('m.User_Phone_Email')"
                clearable
                @change="searchUser"
                @clear="notUser = false"
                style="width:390px;"
              ></el-input>
            </el-form-item>
            <div
              style="color:#fd5849;font-size:12px; margin-bottom: 8px;"
              v-if="ruleForm.sendType == 1 && notUser"
            >
              {{ $t('m.Account_does_not_exist') }}
            </div>
            <div class="userMsgDiv">
              <div
                v-for="item in usersData"
                :key="item.userId"
                class="userMsg"
                v-show="usersData.length > 0 && ruleForm.sendType == 1"
              >
                <span v-if="item.itone"
                  >{{ '+' + item.code }} {{ item.itone | maskedPhone }}</span
                >
                <span v-else>{{ item.email | maskedEmail }}</span>
                <i
                  class="userMsgX el-icon-close"
                  @click="delMsg(item.userId)"
                ></i>
              </div>
            </div>
            <el-form-item prop="userGroupType" v-if="ruleForm.sendType == 2">
              <el-radio-group v-model="ruleForm.userGroupType">
                <el-radio style="margin-bottom:0px;" :label="0">{{
                  $t('m.AccessedButNotRentedUsers')
                }}</el-radio>
                <div class="userGroupHint">
                  {{ $t('m.AccessedButNotRentedUsers2') }}
                </div>
                <el-radio style="margin-bottom:0px;" :label="1">{{
                  $t('m.Users_rented_recently')
                }}</el-radio>
                <div class="userGroupHint">
                  {{ $t('m.Users_rented_recently2') }}
                </div>
                <el-radio style="margin-bottom:0px;" :label="2">{{
                  $t('m.Formerly_active_users')
                }}</el-radio>
                <div class="userGroupHint">
                  {{ $t('m.Formerly_active_users2') }}
                </div>
                <el-radio style="margin-bottom:0px;" :label="3">{{
                  $t('m.Users_more_than24hours')
                }}</el-radio>
                <div class="userGroupHint">
                  {{ $t('m.Users_more_than24hours2') }}
                </div>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="detail_right">
        <div class="detail_left_div" style=" padding-bottom: 20px;">
          <el-form
            label-position="top"
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm2"
          >
            <div class="create_title">{{ $t('m.Push_title') }}</div>
            <div class="create_title2">Tiếng Việt*</div>
            <el-form-item prop="sendTitle.vi">
              <el-input
                v-model="ruleForm.sendTitle.vi"
                :placeholder="$t('m.Please_enter')"
                clearable
                maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
            <div class="create_title2">English*</div>
            <el-form-item prop="sendTitle.en">
              <el-input
                v-model="ruleForm.sendTitle.en"
                :placeholder="$t('m.Please_enter')"
                clearable
                maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
            <div class="create_title2">简体中文*</div>
            <el-form-item prop="sendTitle.zh">
              <el-input
                v-model="ruleForm.sendTitle.zh"
                :placeholder="$t('m.Please_enter')"
                clearable
                maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>

            <div class="create_title">{{ $t('m.Push_content') }}</div>
            <div class="create_title2">Tiếng Việt*</div>
            <el-form-item prop="sendElement.vi">
              <el-input
                v-model="ruleForm.sendElement.vi"
                :placeholder="$t('m.Please_enter')"
                :autosize="{ minRows: 4, maxRows: 6 }"
                type="textarea"
                clearable
                maxlength="110"
                show-word-limit
              ></el-input>
            </el-form-item>
            <div class="create_title2">English*</div>
            <el-form-item prop="sendElement.en">
              <el-input
                v-model="ruleForm.sendElement.en"
                :placeholder="$t('m.Please_enter')"
                :autosize="{ minRows: 4, maxRows: 6 }"
                type="textarea"
                clearable
                maxlength="110"
                show-word-limit
              ></el-input>
            </el-form-item>
            <div class="create_title2">简体中文*</div>
            <el-form-item prop="sendElement.zh">
              <el-input
                v-model="ruleForm.sendElement.zh"
                :placeholder="$t('m.Please_enter')"
                :autosize="{ minRows: 4, maxRows: 6 }"
                type="textarea"
                clearable
                maxlength="110"
                show-word-limit
              ></el-input>
            </el-form-item>

            <div class="create_title2">{{ $t('m.program_img') }}</div>
            <el-form-item>
              <div style="display:flex; width:100%;">
                <el-image
                  class="upload-img"
                  v-show="ruleForm.image"
                  fit="cover"
                  :src="fileUrlFormat(ruleForm.image)"
                  :preview-src-list="[fileUrlFormat(ruleForm.image)]"
                >
                </el-image>

                <el-upload
                  :class="{
                    upload_img2: ruleForm.image,
                    'el_upload1 el_upload2': !ruleForm.image
                  }"
                  drag
                  :action="$store.state.fileUrl"
                  name="files"
                  :on-success="onSuccess"
                  :before-upload="beforeUpload"
                  :show-file-list="false"
                  :file-list="fileList"
                >
                  <div v-show="!ruleForm.image">
                    <img
                      src="@/assets/imgs/ic_add.svg"
                      alt=""
                      class="el_upload_img"
                      style="margin-top:30px"
                    />
                    <div class="el_upload_title">
                      {{ $t('m.Drag_images') }}
                    </div>
                  </div>
                  <div v-show="ruleForm.image" class="upload_btn">
                    <div>{{ $t('m.Change') }}</div>
                    <div
                      @click.stop="
                        ruleForm.image = ''
                        disabled = false
                      "
                    >
                      {{ $t('m.delete') }}
                    </div>
                  </div>
                </el-upload>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      params: {
        search: ''
      },
      ruleForm: {
        id: '', //	消息id
        image: '', //	图片
        sendElement: {
          de: '', //	德语
          en: '', //	英文
          fr: '', //	法语
          vi: '', //	
          it: '', //	
          vi: '', //	越南语
          zh: '' //	中文
        }, //	推送内容(json国际化)
        sendMethod: 1, //	发送方式 1-立即发送 2-指定时间推送
        sendName: '', //	推送名称
        sendTime: '', //	sendMethod为2时必传 推送时间(date-time)
        sendTitle: {
          de: '', //	德语
          en: '', //	英文
          fr: '', //	法语
          vi: '', //	
          it: '', //	
          vi: '', //	越南语
          zh: '' //	中文
        }, //	消息标题(json国际化)
        sendType: 0, //	接收范围：0-全部用户；1-指定用户；2-指定用户组
        state: '', //	状态：0-待推送 1-已推送
        userGroupType: 0, //	指定用户组类型 sendType为2时必传：0-访问未租借；1-近期租借过；2-曾经活跃用户；3-24小时待支付订单用户
        userId: [] //	推送用户id sendType为1时必传
      },
      rules: {
        sendName: [
          {
            required: true,
            message: this.$t('m.This_field_required'),
            trigger: 'blur'
          }
        ],
        userId: [
          {
            type: 'array',
            required: true,
            message: this.$t('m.This_field_required'),
            trigger: 'change'
          }
        ],
        sendTime: [
          {
            required: true,
            message: this.$t('m.This_field_required'),
            trigger: 'blur'
          }
        ],
        'sendTitle.en': [
          {
            required: true,
            message: this.$t('m.Please_enter_title'),
            trigger: 'blur'
          }
        ],
        'sendTitle.zh': [
          {
            required: true,
            message: this.$t('m.Please_enter_title'),
            trigger: 'blur'
          }
        ],
        'sendTitle.vi': [
          {
            required: true,
            message: this.$t('m.Please_enter_title'),
            trigger: 'blur'
          }
        ],
        'sendElement.en': [
          {
            required: true,
            message: this.$t('m.Please_enter_content'),
            trigger: 'blur'
          }
        ],
        'sendElement.zh': [
          {
            required: true,
            message: this.$t('m.Please_enter_content'),
            trigger: 'blur'
          }
        ],
        'sendElement.vi': [
          {
            required: true,
            message: this.$t('m.Please_enter_content'),
            trigger: 'blur'
          }
        ]
      },
      fileList: [],
      platformId: {
        'platform-id': parseInt(this.$cache.get('platformId')),
        add: this.$cache.getLang(),
        'brezze-language':
          this.$cache.getLang() == 'CN' ? 'ZH' : this.$cache.getLang()
      }, //导入请求头
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        },
        shortcuts: [],
        selectableRange:
          new Date().getHours() +
          ':' +
          (new Date().getMinutes() + 0) +
          `:${new Date().getSeconds()} - 23:59:59`
      },
      notUser: false,
      usersData: [],
      createAuth: this.permissionsId(157) //用户详情
    }
  },
  computed: {
    pickerOptions2 () {
      let newVal = new Date(this.ruleForm.sendTime)
      let selectableRange = '00:00:00 - 23:59:00'
      if (
        newVal &&
        newVal.getFullYear() == new Date().getFullYear() &&
        newVal.getMonth() == new Date().getMonth() &&
        newVal.getDate() == new Date().getDate()
      ) {
        //如果为今天，则限制当前时间前的时间+1分钟不能选择。
        selectableRange =
          new Date().getHours() +
          ':' +
          (new Date().getMinutes() + 0) +
          `:${new Date().getSeconds()} - 23:59:59`
      } else {
        selectableRange = '00:00:00 - 23:59:00'
      }
      return {
        selectableRange,
        disabledDate (time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        }
      }
    }
  },
  created () {
    if (this.$route.query.params && this.createAuth) {
      this.getMessags()
    }
  },
  mounted () {},
  methods: {
    // 获取消息编辑信息
    getMessags () {
      this.$api.messagePush
        .getMessags({ id: JSON.parse(this.$route.query.params).id })
        .then(res => {
          if (this.$ok(res)) {
            if (res.data.sendType == 1) {
              this.usersData = res.data.userInfo
            }
            this.ruleForm = res.data
            this.ruleForm.sendElement = JSON.parse(this.ruleForm.sendElement)
            this.ruleForm.sendTitle = JSON.parse(this.ruleForm.sendTitle)
            delete this.ruleForm.createTime
            delete this.ruleForm.userInfo
            if (JSON.parse(this.$route.query.params).state == 1) {
              this.ruleForm.id = ''
            }
            this.ruleForm.userId = []
          }
        })
    },
    // 搜索用户
    getUsers () {
      this.$api.messagePush.getUser(this.params).then(res => {
        if (this.$ok(res)) {
          if (res.data) {
            this.params.search = ''
            this.notUser = false
            res.data.forEach(item => {
              this.addObjectById(this.usersData, item)
            })
          } else {
            this.notUser = true
          }
        }
      })
    },
    //确认搜索
    searchUser () {
      if (!this.params.search) {
        return
      }
      this.getUsers()
    },
    addObjectById (array, object) {
      const idExists = array.some(item => item.userId === object.userId)
      if (!idExists) {
        array.push(object)
      }
    },
    delMsg (id) {
      this.usersData = this.usersData.filter(item => item.userId !== id)
    },

    //上传成功回调
    onSuccess (res, file, fileList) {
      this.ruleForm.image = file.response.data.value
      // console.log(this.fileUrlFormat(this.ruleForm.image))
    },

    //上传广告前限制
    beforeUpload (file) {
      // console.log(file.size)
      const isJPG = this.$dict.file.imageType.indexOf(file.type) != -1
      const isLt1M = file.size / 1024 / 1024 < 0.3
      // console.log(isLt1M)
      if (!isJPG) {
        this.$message.warning(this.$t('m.Upload_image_type'))
        return false
      }
      if (!isLt1M) {
        this.$message.warning(this.$t('m.File_size300'))
        return false
      }
      return isJPG && isLt1M
    },

    async submit () {
      try {
        await Promise.all([
          this.$refs.ruleForm1.validate(),
          this.$refs.ruleForm2.validate()
        ])
        this.ruleForm.sendType == 1
          ? (this.ruleForm.userId = this.usersData.map(item => item.userId))
          : ''
        // console.log(this.ruleForm)
        if (this.ruleForm.sendType == 1 && this.ruleForm.userId.length == 0) {
          return this.$message.error(this.$t('m.Select_specify_user'))
        }
        this.$api.messagePush.createModify(this.ruleForm).then(res => {
          if (this.$ok(res)) {
            this.$message.success(res.message)
            if (!this.ruleForm.id) {
              this.remPageNum()
            }
            this.back()
          } else {
            this.$message.error(res.message)
          }
        })
      } catch (error) {
        // 验证失败
        // console.log('error submit !')
        return
      }
    }
  }
}
</script>
<style>
.el_date_picker .el-picker-panel__sidebar {
  display: none;
}
.el_date_picker .el-picker-panel__sidebar + .el-picker-panel__body {
  margin-left: 0;
}
.el_date_picker .el-picker-panel__content {
  width: initial !important;
}
.el_date_picker .el-date-table td.current:not(.disabled) span {
  background: var(--text-color);
}
.el_date_picker .el-date-table td.today span {
  color: var(--text-color) !important;
  background: #fff !important;
}
.el_date_picker .el-button {
  color: #39404d;
}
.el_date_picker .el-button--text {
  color: var(--text-color);
}
.el_date_picker .el-button--text:hover {
  color: var(--text-color) !important;
}
.el_date_picker .el-button.is-plain:hover {
  color: var(--text-color) !important;
  border-color: var(--text-color) !important;
}
.el_date_picker .el-picker-panel__icon-btn:hover {
  color: var(--text-color);
}
.userGroupHint {
  padding: 6px 0 16px 0;
  font-size: 12px !important;
  color: #888888;
  line-height: 14px;
}
</style>
<style scoped lang="scss">
.el_upload1 {
  width: 100%;
  height: 116px;

  ::v-deep .el-upload {
    width: 100% !important;
  }

  ::v-deep .el-upload-dragger {
    width: 100% !important;
    height: 116px !important;
    background: #fafafc !important;
    border: 1px solid #ececee !important;
    border-radius: 6px !important;
  }

  ::v-deep .el-upload-dragger.is-dragover {
    border: 1px dashed var(--text-color) !important;
  }

  .el_upload_img {
    width: 32px;
    height: 32px;
    margin: 24px 0 20px 0;
  }

  .el_upload_title {
    font-size: 14px;
    font-weight: 400;
    text-align: center;
    color: #646b80;
    line-height: 16px;
    padding: 0 24px;
  }
}

.el_upload2 {
  height: 128px;

  ::v-deep .el-upload-dragger {
    height: 128px !important;
  }
}
.upload_img2 {
  ::v-deep .el-upload-dragger {
    display: flex;
    align-items: end;
    height: 88px !important;
    // width: 88px !important;
    border: none !important;
  }
}
.upload_btn {
  display: flex;
  div {
    font-size: 14px;
    font-weight: 400;
    text-align: left;
    color: var(--text-color);
    line-height: 20px;
    margin-left: 12px;
  }
}
.userMsgDiv {
  display: flex;
  flex-wrap: wrap;
  .userMsg {
    padding: 6px 8px;
    background: #fff7e7;
    border-radius: 3px;
    margin: 0 10px 10px 0;
    .userMsgX {
      padding-left: 10px;
      cursor: pointer;
    }
  }
}
</style>
